Updating a Database Using Flash MX Professional 2004
by Mark Rausch
With the release of Macromedia Flash MX Data Connection Kit, Macromedia introduced the data-aware Firefly Components suite, which includes a DataSet component and plug-ins for connecting to various databases. Flash MX Professional 2004 includes updated versions of these components that work with databinding and take advantage of various Macromedia Flash Player enhancements.
In this article I show you how to build a complete Flash application that uses the DataSet, DataGrid, RDBMSResolver components together with a ColdFusion component to read data from an Access database, edit the data, and update the database. I also detail the format of the resolver's update and result packets and discuss how to build your own server functions to parse the XML, update the database, and construct a result packet.
Requirements
To complete this tutorial you will need to install the following software and files:
Macromedia Flash MX Professional 2004
Macromedia ColdFusion MX
Note: If ColdFusion MX is installed on a different machine than the one on which you build the Flash movie, you must place the proper IP address in the URL to access the component.
You should also be at least minimally familiar with creating and running Flash movies using Flash MX 2004.
Download sample files
rdbms_resolver_sources.zip (266K)
Note: The sample ColdFusion Component gives you the ability to run a query statement against any ColdFusion data source that you have set up on your machine. You should install it to the web root folder only within a development environment behind a secure firewall or on a computer that is not connected to the Internet! If you intend to use this component in a production environment you must take the necessary steps to secure it.
The Basics
Before I get too deep into the technical details, I'd like to discuss some of the basics about the concepts and components you'll be dealing with.
Terminology
Throughout this article, I am using the following terms:
- DeltaPacket: An object produced by a DataSet component that contains a list of the changes that were made to its data.
- update packet: An XML document that describes the content of a DeltaPacket. I discuss the format of this (and the following) XML document in detail in this tutorial.
- result packet: An XML document that contains the results of the operations in the corresponding update packet.
- server function: Code residing on a server in the form of an ASP page, a Java servlet, a ColdFusion component, and so on. The sample ColdFusion component that is part of this tutorial's sample files provides an example of this functionality.
What Are Resolvers and How Do They Work with DataSets?
In Flash MX Professional 2004, resolvers are essentially two-way translators between a DataSet and the outside world. To remain as flexible as possible, the DataSet only understands DeltaPackets. If you want to store changes to a dataset persistently, you must use a resolver to turn the DeltaPacket into a more useful form.
Every resolver understands how to break down a DeltaPacket and extract the information within it. Each type of resolver produces a different translation of that information. For example, the XUpdateResolver translates DeltaPackets into XUpdate, a language for updating XML.
The RDBMSResolver Component
In this article I use the RDBMSResolver component to send the changes in a dataset to a ColdFusion component that parses it into SQL and saves it to a SQL database.
Why bother going thru the extra step of sending the DeltaPacket to a component like this CFC? Why not bypass the component and have the resolver produce SQL? Two reasons: There are too many variants of SQL, each with its own slight differences in syntax, field formatting requirements, and so on. Also, for the DataSet component to function properly, it needs to receive results that contain transaction IDs and operation IDs so that individual results can be matched with the row from which they originated. SQL syntax does not support this functionality.
So, instead of producing SQL, the RDBMSResolver component produces XML in a format that can be easily parsed and turned into SQL in the required dialect. The same server function that parses it can individually apply operations to the database, determine the result of each, and return a result packet containing them.
Update Packets in Detail
An update packet is an XML document that describes the contents of a DeltaPacket. The RDBMSResolver component's update packet contains enough information to be able to construct SQL statements that mirror the operations that were performed to the data in the DataSet. The following snippet shows a sample update packet.
<update_packet tableName="customers" nullValue="{_NULL_}" transID="46386292065">
<delete id="11295627477">
<field name="id" type="numeric" oldValue="10" key="true"/>
</delete>
<insert id="12345678901">
<field name="id" type="numeric" newValue="20" key="true"/>
<field name="FName" type="string" newValue="Davey" key="false"/>
<field name="LName" type="string" newValue="Jones" key="false"/>
</insert>
<update id="98765432101">
<field name="id" type="numeric" oldValue="30" newValue="40" key="true"/>
<field name="FName" type="string" oldValue="Peter" newValue="Mickey" key="false"/>
<field name="LName" type="string" oldValue="Tork" newValue="Dolenz" key="false"/>
</update>
</update_packet>
Every update packet contains the <update_packet> node
as the top level node. This node holds information such as the name of
the table to be updated, a string that is used to signal null field values,
and the transaction ID for this update packet. The tableName and nullValue attributes
are used when parsing the packet into SQL statements and come from properties
on the resolver. The transID value is created by the DataSet
component and should be returned to the resolver in the result packet.
Below the top level node are the operation nodes: <insert>, <delete>,
or <update>. These nodes are unlimited in number and
can be in any order. Each operation node has an id attribute that the
DataSet component uses to uniquely identify the operation.
Each operation node contains child nodes that list fields for the purpose
of either giving key field information to locate the correct record,
or for setting a new value for that field. The following table lists
the attributes that can be on a <field> node.
| Attribute | Description |
|---|---|
name |
Name of the field. |
type |
Data type of the field. |
key |
True if the field is a key field; False otherwise. |
oldValue |
Original value of the field when obtained from the table. This attribute does not exist for insert operations. |
newValue |
Most recent value set for the field within the DataSet component. This attribute only exists if the field value has been changed. |
Since the <field> node can have both old and new
values, a single node can simultaneously identify a key field and update
that field's value. For example:
<field name="id" type="numeric" oldValue="30" newValue="40" key="true"/>
Result Packets in Detail
A result packet is an XML document that contains the results of the operations in the corresponding update packet. A result packet can provide a simple response to the DataSet component, providing feedback that all operations were performed successfully, or it can be more complex and include error messages and information about changed field values.
The following example shows a simple result packet:
<results_packet transID="46386292065"/>
By returning the transID from the update packet, the result
packet informs the DataSet component that the update packet was received
and processed. No additional information needs to be sent when there
are no errors and no fields to update.
A more elaborate result packet (with both errors and field change information) might look like this:
<results_packet transID="46386292065">
<operation op="delete" id="11295627479" msg="Record not found" />
<operation op="update" id="02938027477">
<field name="id" msg="Invalid field value" />
</operation>
<operation op="insert" id="02938027470">
<field name="id" curValue="105034" />
</operation>
</results_packet>
This packet shows the results of an update packet where two of the operations had errors. The third operation succeeded, but a field was updated by the server function (I'll discuss this shortly).
Underneath the top level <results_packet> node, there
can be any number of <operation> nodes. Each <operation> node
must have an op attribute with the value of insert, delete,
or update, and an id attribute that holds the
ID of the operation from the update packet. If the operation had an error,
the node should also have a msg attribute that contains
the error message text.
Each <operation> node can contain an unlimited number
of <field> nodes. These nodes should have a name attribute
that contains the field name, a msg attribute to flag field-level
error messages, and a curValue attribute that indicates
the field's most current value on the server.
A non-empty msg attribute in any <operation> or <field> node
tells the DataSet component that the operation that contains the msg attribute
failed, and provides the specific reason for the failure.
Updating Fields on the Server
As I mentioned above, the result packet can contain updated field values. Why? One usage is to allow for scenarios where new records are submitted to a server, and a function on the server sets the primary key value for the new record. This is often the case in multiuser systems. Since these updated values can be returned in the result packet, the DataSet component can be notified of these new values without having to make another request for the same data.
In the sample results packet above, the final <operation> node
is an example of this scenario. The node indicates that the insert operation
was performed successfully, and that the new record's id field
was set to 105034. When that result is received by the DataSet component,
it locates the record identified by the operation's id attribute,
and updates the record with that value. Any subsequent update packets
that contain edits of that record correctly identify the record as having
an id field with a value of 105034.
Transaction IDs and Operation IDs
Transaction IDs and operation IDs are used by the DataSet for bookkeeping. They help it track records sent to and received from the server. For ease of display, I have shortened the transaction ID value. The actual value is much longer and includes a timestamp to help make it unique. When parsing the update packet, it's important to retain these values and return them in the result packet.
The DataSet produces a DeltaPacket when you call its applyUpdates() method.
If results from the previous DeltaPacket have not yet been returned,
the DataSet will still produce a new DeltaPacket containing only the
data that has been changed since the last one. So a DataSet at times
can be waiting for results from two or more DeltaPackets. You can see
how important it is to return these IDs.
How the DataSet Handles Errors
When the DataSet receives results, in addition to updating any fields
that were modified on the server, it looks for any operations that returned
errors. Each operation with an error is placed back into the queue to
go out in the next DeltaPacket, and each error is put into an array.
The DataSet then fires its onResolveDelta event, making
that error array available as the data property of the dispatched event.
A simple example of displaying errors is included in the sample Flash
application.
A Sample Update Packet Parser
Now that you have some information on the update packet and result packet formats, it's time to look at an example parser in detail. The following code snippets are from the provided ColdFusion component.
<cffunction name="saveSQLData" access="remote" returntype="string">
<cfargument name="datasource" type="string" required="true">
<cfargument name="deltaData" type="string" required="true">
...
</cffunction>
The saveSQLData() function performs the following tasks:
-
It parses the update packet, pulling out top level node data and the operation nodes.
<!--- Get the nodes from the update packet ---> <cfset deltaXML=XmlParse(deltaData)> <cfset deltaNodes=XmlSearch(deltaXML, "update_packet/*")> <cfset nodecount=ArrayLen(deltaNodes)> <!--- Now get the values passed in the update packet ---> <cfset nullValue=deltaXML.update_packet.XmlAttributes.nullValue> ...
-
It creates a SQL statement for each operation based on the type of the operation node.
<cfloop index="deltaNum" from="1" to=#nodecount#> <cfset keyFldNodes=XmlSearch(deltaXML, "update_packet/*[#deltaNum#]/field[@key='true']")> <cfset modFldNodes=XmlSearch(deltaXML, "update_packet/*[#deltaNum#]/field[@newValue]")> ... <!--- Assemble the remainder of the SQL statement based on this node's type ---> <!--- update ---> <cfif deltaNodes[deltaNum].xmlname is "update"> ... <!--- insert ---> <cfelseif deltaNodes[deltaNum].XmlName is "insert"> ... <!--- delete ---> <cfelseif #deltaNodes[deltaNum].XmlName# is "delete"> </cfloop> -
It calls the
formatFieldValue()method to format each field value based on its data type. It also checks for and modifies null values.<cfset valList=formatFieldValue(modFldNodes[fieldNum].XmlAttributes.newValue, modFldNodes[fieldNum].XmlAttributes.type, nullValue)>
-
It calls the
getNextID()function to create a new numeric key value for a specified field on inserted records. Note that the component knows for which field to generate a new key value, because the name is passed in via the update packet. This is an example of how you can add and pass in data to control how your server function will work. Alternately, in the same position in the ActionScript code, you could modify values in the update packet if you found that necessary.<cfset autoIncValue=getNextID(datasource, tableName, autoIncFldName)>
-
It runs each SQL statement against the database.
<!--- Run the generated SQL Statement against the database and catch errors ---> <cftry> <cfquery name="updateTable" datasource=#datasource# dbtype="odbc">#PreserveSingleQuotes(sqlStmt)# </cfquery> ... </cftry> -
It checks the result of the SQL operation and saves any errors to the result packet. Since each SQL operation is done individually, the CFC can match up any errors with the corresponding operation in the result.
<cfcatch type="database"> <!--- Add a new error node to the XML result packet ---> <cfset resultPacket = "#resultPacket# <operation ... </cfcatch> -
It puts the new key value for inserted records into the result packet.
<cfif (deltaNodes[deltaNum].XmlName is "insert") and (autoIncFldName NOT EQUAL "")> <cfset resultPacket = "#resultPacket# <operation op=""update... </cfif> - It returns the result packet.
Take note that nothing in the sample ColdFusion component is hard coded to work just with the data source or the table specifically. Those values are passed in either as a parameter or in the update packet. So, this is a fairly full-featured example that will work with other tables or databases after some minor changes.
Setting up the ColdFusion Component
To set up the ColdFusion component, follow these steps:
- Save the Access database file TimeTrax.mdb in a folder (for example, C:\RDBMS_CFC\TimeTrax.mdb)
-
Add a ColdFusion Data Source for the TimeTrax.mdb file.
- Open ColdFusion administrator.
- Click the Data Sources link.
- Type TimeTrax in the Data Source Name text box, select Microsoft Access from the Driver combo box, and click the Add button.
- Click the Browse button and navigate to the TimeTrax.mdb.
- Click the Submit button.
- Verify that the new Data Source has a status of OK.
-
Save the RDBMSProcessor.cfc file into the web root of your ColdFusion directory.
- In version 6.0, put the file in the wwwroot directory under your ColdFusion install directory.
- In version 6.1, put it in the JRun4\servers\cfusion\cfusion-ear\cfusion-war directory.
Note: The sample ColdFusion Component gives you the ability to run a query statement against any ColdFusion data source that you have set up on your machine. You should install it to the web root folder only within a development environment behind a secure firewall or on a computer that is not connected to the Internet! If you intend to use this component in a production environment you must take the necessary steps to secure it.
Building the Flash Application
Now I'm going to show you how to build a simple application that makes use of the ColdFusion component to load data from the database and save data back to it.
- Open Flash MX Professional 2004 and create a new Flash document.
- Drag a DataSet component to the Stage and name it ds. Drag a DataGrid component to the Stage, name it grid, set its x,y position to 0,0, set its width to 540, and set its height to 240. In the Component Inspector, set its editable property to true.
-
Databind ds.dataProvider to grid.dataProvider by following these steps:
- Select the DataSet component on the Stage and choose the bindings tab in the Component Inspector.
- Click the + button to add a new binding.
- In the Add Binding dialog box, select the dataProvider property and click the OK button.
- In the Component Inspector, select the bound to property of the new binding, and click the button next to it.
- In the Bound To dialog box, select the DataGrid, <grid> item in the Component Path list box. You'll see a list of the DataGrid properties in the Schema Location list box on the right.
- Select the dataProvider property, and click the OK button to complete your task (see Figure 1).

Figure 1. Task completed: ds.dataProvider is bound to grid.dataProvider
- Databind ds.selectedIndex to grid.selectedIndex following in outline the directions in step 3.
-
Add schema to the DataSet component to describe the expected fields. Click the DataSet component, and select the Schema tab in the Component Inspector.
- Click the leftmost + button to add a component property. Type id into the field name text box, and select Number from the data type drop-down list. This tells the DataSet to expect an id field in the data, and that its value is a number.
- Following the instructions above, add the following fields and data types: rate as Number; duration as Number; billable as Boolean; notes as String (see Figure 2).

Figure 2. The finished schema of the DataSet component
-
Click the Stage to deselect all selected components and type the following code into the Actions panel (this code sets up a connection to the ColdFusion component and calls the getSQLData() function to get data):
#include "NetServices.as" #include "NetDebug.as" //Set up the NetServices connection to the ColdFusion component. var con:NetConnection = NetServices.createGatewayConnection( "http://localhost:8300/flashservices/" ); _global.srv = con.getService( "rdbmsProcessor", this ); //Call the function with a query to get the data. _global.srv.getSQLData( "timetrax", "select notes, billable, duration, rate, duration, id from timeentry" ); //Called with the result from the getSQLData function, this places the data into the dataset. function getSQLData_Result( result ) { ds.dataProvider = result; } -
To add the ability to add new records, drag a Button control to the Stage, set its label property to Add and type the following code into the Actions panel:
on(click){ _parent.ds.addItem(); } -
To add the ability to delete records, drag another Button control to the Stage, set its label property to Delete and type the following code into the Actions panel:
on(click){ _parent.ds.removeItem(); } -
Test the movie. Verify that you are getting data in the grid and that you can add, edit, and delete records. At this point, there is no way to save your changes. If you can not modify records, review the steps above, and verify that you have ColdFusion MX set up correctly with the ColdFusion component and database by typing the following into your browser:
http://localhost:8300/rdbmsProcessor.cfc?method=getSQLData&dataSource=timetrax&sqlStatement=select%20*%20from%20timeentry - To add the ability to save your changes, drag an RDBMSResolver component to the Stage, name it rs.
-
In the Component Inspector, and specify the following properties:
- Set the tableName property to TimeEntry.
- Click the button next to the fieldInfo property.
- In the Values dialog box, click the + button.
- In the area below, type id into the fieldName property, and click the OK button (see Figure 3).

Figure 3. Filling in the Values dialog box
This instructs the RDBMSResolver component that the id field is the key field for this table (see Figure 4).

Figure 4. The RDBMSResolver component configured
-
With the RDBMSResolver component still selected, type the following into the Actions panel:
on(beforeApplyUpdates) { //Add an attribute to the update packet to tell the CFC //that we want it to generate values for the id field var firstChild:XMLNode = eventObj.updatePacket.firstChild; firstChild.attributes.autoIncField = "id"; trace(eventObj.updatePacket); //Now send the update packet to the parsing method in the CFC _global.srv.saveSQLData( "timetrax", eventObj.updatePacket.toString()); } - Databind rs.deltaPacket to ds.deltaPacket using in outline the directions in step 3.
-
Drag a Button control to the Stage, set its label property to Save, and type the following into the Actions panel:
on(click) { _parent.ds.applyUpdates(); } -
To catch the result packet coming back from the CFC, click the Stage to deselect any selected components, and type the following code into the Actions panel:
//Catches the result packet returned by the CFC, and puts it into the resolver function saveSQLData_Result( result ) { trace(result); var resultDoc:XML = new XML(); resultDoc.ignoreWhite = true; resultDoc.parseXML(result); rs.updateResults = resultDoc; } -
To add in the ability to view errors returned in the result packet, select the DataSet and type the following in the Actions panel:
on(resolveDelta) { var errs:Array = eventObj.data; for( var i:Number=0; i<errs.length; i++ ) { trace( errs[i].getMessage()); } }
That's it. You can now play around with the application. Try adding, editing, and deleting records. Take a look at the contents of the update packet and result packets in the output panel. Notice how the value for the id field is automatically created within the server function and how the DataSet picks up and displays the updated value in the grid.
Of course, you could also enhance the functionality of this application by adding the ability to deal with errors returned from the server. You can see a working example of error resolution in Paul Gubbay's Time Entry sample application.
Summary
This article focuses on how to deal with packets so you can have an application that updates a database. As you have seen, with very few lines of ActionScript code, this application is able to load data from a table, edit that data, and save it back to the database. You have also seen how it is possible to pass additional control information along to server functions through update packets, and how the server function can update fields and pass those values back to the DataSet to be updated, thus conserving network bandwidth. When Macromedia releases the new Remoting connector, this application will be even easier to build since you would not have to write the code to connect to the CFC, make the function calls, and manually bring in the data and results.
If necessary, you can easily modify the provided ColdFusion component to produce a different SQL syntax that would work with other RDBMS databases in the same fashion. If you are familiar with ASP, .NET, or Java Servlets, you should also be able to use this component as a template for building this functionality in your language of choice.